//
//  gradientLayerView.m
//  gradientlayer
//
//  Created by zmj27404 on 16/2/17.
//  Copyright © 2016年 zmj27404. All rights reserved.
//

#import "gradientLayerView.h"
#import <GLKit/GLKit.h>
#import "NSString+Scale.h"

#define SINGLE_LINE_WIDTH           (1 / [UIScreen mainScreen].scale)
#define SINGLE_LINE_ADJUST_OFFSET   ((1 / [UIScreen mainScreen].scale) / 2)

@interface gradientLayerView ()
{
#pragma mark 分时图中的图层,添加到realTimeView上
    CAGradientLayer *gradientLayer; //渐变图层
    CAShapeLayer *shaperLayer;  //渐变mask图层
    CAShapeLayer *lineLayer;    //渐变图层外的线图层
    UIView *realTimeView;       //实时视图

#pragma mark K线图中的视图,添加到kView;
    UIView *kView;
    
#pragma mark -  最上面一层的视图
    CAShapeLayer *midLayer;          //中间线图层
    CAShapeLayer *rvLayer;      //垂直曲线图层
    CAShapeLayer *circleLayer;  //点圆圈图层
    CATextLayer *showPriceLayer;    //显示价格和时间的图层
    
#pragma mark 直接添加到self.layer上
    CALayer *borderLayer;       //边框图层,分时图,可以切换成K线图
    CATextLayer *curTextLayer;  //当前数据图层
    NSArray <CATextLayer*> *labVTextArray;   //数字图层数组(垂直方向)
    UIBezierPath *path; //保存当前路径的除最后一个点的路径对象
    NSArray <CATextLayer*> *labHTextArray;
    
    CGRect innerRect;
    NSArray *pointArray;     //开高低收,以及时间数据源
    NSArray *closeArray;            //收盘价数组,用于绘制分时图
    double maxHeight, minHeight;    //物理像素所代表的最大值,最小值
    double maxArrayHeight, minArrayHeight;  //数组中所代表的最大值,最小值
    double everyXSpace; //每物理像素所代表的宽度
    double everyYSpace; //每单位虚拟所代表的物理高度=(maxHeight-minHeight)/CGRectGetHeight(innerRect);
    NSUInteger startIndex;  //分时线视图上的起始位置
    NSUInteger startIndexAtArray;   //数组中绘图的起始位置
    NSUInteger currentCount;
    BOOL labInRight;    //文本是否在右边
    NSDateFormatter *dateFormatter; //数据源中的时间格式
    NSDateFormatter *toDateFormatter;   //转换的时间格式
    NSValue *curPointValue;
}
@end

static double const MAXH = 0.0;         //最大值
static double const MINH = 100000000.0; //最小值
static double const SHADOWNHEIGHT = 0.1; //固定间距阴影所占的比例
static double const LABCOUNT = 11;       //Lab的数量,间距
static double const VERTICALCOUNT = 5;  //列的数量
static double const LABHEIGHT = 15;     //lab高度
static double const LABSPACETOEDGE = 3; //lab距左边的间距

@implementation gradientLayerView
#pragma mark - 初始化方法
- (instancetype)initWithFrame:(CGRect)frame andPoints:(NSArray *)points maxCount:(NSUInteger)count layerType:(LayerType)type{
    if (self = [super initWithFrame:frame]) {
        [self initView];
        _maxCount = count;
        pointArray = [points mutableCopy];
        _layerType = type;
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    if (self = [super initWithCoder:aDecoder]) {
        [self initView];
        [self updateBorder];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self initView];
        [self updateBorder];
    }
    return self;
}

- (void)initView {
    pointArray = @[].mutableCopy;
    path = [UIBezierPath bezierPath];
    path.lineCapStyle = kCGLineCapRound;
    path.lineJoinStyle = kCGLineJoinRound;
    _maxCount = 300;
    maxHeight = MAXH;
    maxArrayHeight = MAXH;
    minArrayHeight = MINH;
    minHeight = MINH;
    startIndex = 0;
    currentCount = _maxCount;
    _edgeInsets = UIEdgeInsetsMake(5, 5, 20, 50);
    _lineColor = [UIColor yellowColor];
    _lineWidth = /**SINGLE_LINE_WIDTH*/ 2.0;
    _midLineColor = [UIColor whiteColor];
    _midLineWidth = 2 * SINGLE_LINE_WIDTH;
    _borderHorizonlColor = [UIColor colorWithRed:70/255.0 green:70/255.0 blue:70/255.0 alpha:1.0];
    _borderHorizonlLineWidth = 2 * SINGLE_LINE_WIDTH;
    _borderVerticalColor = [UIColor colorWithRed:33/255.0 green:33/255.0 blue:33/255.0 alpha:1.0];
    _borderVerticalLineWidth = SINGLE_LINE_WIDTH;
    _borderBackgroundColor = [UIColor colorWithRed:5/255.0 green:5/255.0 blue:5/255.0 alpha:1.0];
    _labFontSize = 13.0f;
    _labForegroundColor = [UIColor whiteColor];
    labInRight = _edgeInsets.right > _edgeInsets.left;
    _scale = 2;
    _backgroundLineType = backLineType_Real;
    _layerType = LayerType_RealTime;
    _DontChangeDatas = YES;
    dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"YY-MM-dd HH:mm:ss"];
    dateFormatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:8];
    toDateFormatter = [[NSDateFormatter alloc] init];
    [toDateFormatter setDateFormat:@"HH:mm"];
    toDateFormatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:8];
    
    self.layer.backgroundColor = [UIColor colorWithRed:23/255.0 green:23/255.0 blue:23/255.0 alpha:1.0].CGColor;
}

#pragma mark - Y轴左边转换及点位转换
- (double)everyXSpace{
    return (double)CGRectGetWidth(innerRect) / (_maxCount - 1);
}

- (double)everyYSpace {
    return (maxHeight - minHeight) / (double)CGRectGetHeight(innerRect);
//    return (maxArrayHeight - minArrayHeight) / (double)CGRectGetHeight(innerRect) * (1 - 2 * SHADOWNHEIGHT);
}

- (void)getMaxAndMinHeight:(NSArray *)array from:(NSUInteger)start {
    if (array.count == 0) {
        return;
    }
    maxHeight = MAXH;
    maxArrayHeight = MAXH;
    minHeight = MINH;
    minArrayHeight = MINH;
    for (NSInteger i = start; i < array.count; i++) {
        double strDoubule = [array[i] doubleValue];
        if (strDoubule > maxArrayHeight) {
            maxArrayHeight = strDoubule;
        }else if (strDoubule < minArrayHeight) {
            minArrayHeight = strDoubule;
        }
    }
    [self getLastMaxAndMinHeightByLastHeight:[[array lastObject] doubleValue]];
}

#pragma mark 最大值,最小值跟数组中最后一条作比较(最后一条居中)
/**
 *  根据最后一条数据高度,确定整个布局的高度(最大值),0(最小值)
 *
 *  @param lastHeight 最后一条数据的高度
 */
- (void)getLastMaxAndMinHeightByLastHeight:(CGFloat)lastHeight{
#if 0
    //以最后一个点居中绘图
    double topSpace = maxArrayHeight - lastHeight;
    double bottomSpace = lastHeight - minArrayHeight;
    //虚拟间距(上->中或者中->下)
    double shadownSpace = MAX(topSpace, bottomSpace);
    //物理间距
    double shadownHeight = SHADOWNHEIGHT * CGRectGetHeight(innerRect);
    //每单位像素所代表的高度(物理间距/虚拟间距)
    everyYSpace = (2 * shadownHeight) / shadownSpace;
    //最上面一层的间距跟当前最大值的虚拟间距
    CGFloat space = shadownHeight / everyYSpace;
    //最大值(虚拟):最后值 + space + 当前最大值与中间值的虚拟间距
    maxHeight = lastHeight + space + shadownSpace;
    minHeight = lastHeight - space - shadownSpace;
#else
    //空格间隙为总高度0.05绘制
    double height = CGRectGetHeight(innerRect);
    double shadownHeight = (1 - 2 * SHADOWNHEIGHT) * height;
    everyYSpace = (maxArrayHeight - minArrayHeight) / shadownHeight;
    maxHeight = maxArrayHeight + SHADOWNHEIGHT * height * everyYSpace;
    minHeight = minArrayHeight - SHADOWNHEIGHT * height * everyYSpace;
#endif
}

//返回物理高度
- (double)yHeight:(double)heigt {
    return (heigt - minHeight) / everyYSpace;
//    return (heigt - minArrayHeight) / everyYSpace + SHADOWNHEIGHT * heigt;
}

- (CGPoint)startPoint {
    double firstY = [self yHeight:[closeArray[startIndexAtArray] doubleValue]];
    return CGPointMake(startIndex * everyXSpace, firstY);
}

#pragma mark - setter方法
- (void)setLineColor:(UIColor *)lineColor{
    _lineColor = lineColor;
    lineLayer.strokeColor = lineColor.CGColor;
}

- (void)setLineWidth:(CGFloat)lineWidth{
    _lineWidth = lineWidth;
    lineLayer.lineWidth = lineWidth;
}

- (void)setMidLineColor:(UIColor *)midLineColor {
    _midLineColor = midLineColor;
    midLayer.backgroundColor = midLineColor.CGColor;
}

- (void)setMidLineWidth:(CGFloat)midLineWidth {
    _midLineWidth = midLineWidth;
    
    CGRect frame = midLayer.frame;
    frame.origin.y = CGRectGetMidY(frame) - midLineWidth / 2.0;
    frame.size.height = midLineWidth;
    midLayer.frame = frame;
}

- (void)setEdgeInsets:(UIEdgeInsets)edgeInsets {
    _edgeInsets = edgeInsets;
    labInRight = edgeInsets.right > edgeInsets.left;
    
    [self updateBorder];
}

- (void)setBorderHorizonlColor:(UIColor *)borderHorizonlColor {
    _borderHorizonlColor = borderHorizonlColor;
    [self updateBorder];
}

- (void)setBorderHorizonlLineWidth:(CGFloat)borderHorizonlLineWidth {
    _borderHorizonlLineWidth = borderHorizonlLineWidth;
    [self updateBorder];
}

- (void)setBorderVerticalColor:(UIColor *)borderVerticalColor {
    _borderVerticalColor = borderVerticalColor;
    [self updateBorder];
}

- (void)setBorderVerticalLineWidth:(CGFloat)borderVerticalLineWidth {
    _borderVerticalLineWidth = borderVerticalLineWidth;
    [self updateBorder];
}

- (void)setBorderBackgroundColor:(UIColor *)borderBackgroundColor {
    _borderBackgroundColor = borderBackgroundColor;
    [self updateBorder];
}

- (void)setGradientColor:(NSArray *)gradientColor{
    _gradientColor = gradientColor;
    gradientLayer.colors = _gradientColor;
}

- (void)setScale:(NSUInteger)scale {
    _scale = scale;
    [self setLabTextLayerText];
}

- (void)setBackgroundLineType:(backLineType)backgroundLineType {
    _backgroundLineType = backgroundLineType;
    [self updateBorder];
}

- (void)setDataPoints:(NSArray *)dataPoints {
    pointArray = [NSArray arrayWithArray:dataPoints];
    [self drawLine];
}

- (void)setMaxCount:(NSUInteger)maxCount {
    _maxCount = maxCount;
    [self drawLine];
}

#pragma mark - 核心绘分时线
- (void)show {
    [self updateBorder];
    [self drawLine];
}

- (void)drawLine {
    if (pointArray.count > 0) {
        [path removeAllPoints];

        //分时图取收盘价作为数组
        NSMutableArray *tmpArray = @[].mutableCopy;
        for (NSArray *tmp in pointArray) {
            [tmpArray addObject:tmp[3]];
        }
        closeArray = [tmpArray copy];
        
        //画路径
        BOOL flag = closeArray.count > _maxCount;
        startIndex = flag ? 0 : _maxCount - closeArray.count;
        currentCount = MIN(closeArray.count, _maxCount);
        startIndexAtArray = flag ? closeArray.count - _maxCount : 0;
        
        //这里获取borderLayer中所代表的最大值和最小值
        [self getMaxAndMinHeight:closeArray from:startIndexAtArray];
        everyXSpace = [self everyXSpace];
        everyYSpace = [self everyYSpace];
        
        _lineWidth = 2.0f;
        if (everyXSpace < _lineWidth) {
            _lineWidth = 1.0f;
        }
        
        CGPoint startPoint = [self startPoint];
        [path moveToPoint:startPoint];
        //除最后一个点的路径
        for (NSInteger i = 0; i < currentCount - 1; i++) {
            @autoreleasepool {
                [path addLineToPoint:CGPointMake((startIndex + i) * everyXSpace, [self yHeight:[closeArray[i + startIndexAtArray] doubleValue]])];
            }
        }
        
        [self setCoreLayerPath:[self pathAddPath:path LastHeight:[self yHeight:[closeArray[currentCount -1 + startIndexAtArray] doubleValue]]]];
    }
}

- (UIBezierPath *)pathAddPath:(UIBezierPath *)path1 LastHeight:(CGFloat)height {
    //加上最后一个点的路径，进行绘图
    UIBezierPath *path2 = [UIBezierPath bezierPathWithCGPath:path1.CGPath];
    [path2 addLineToPoint:CGPointMake(path2.currentPoint.x + everyXSpace, height)];
    return path2;
}

- (void)setCoreLayerPath:(UIBezierPath *)paths {
    if (realTimeView == nil) {
        realTimeView = [[UIView alloc] initWithFrame:innerRect];
        realTimeView.backgroundColor = [UIColor clearColor];
        realTimeView.layer.geometryFlipped = YES;
        realTimeView.userInteractionEnabled = YES;
        [self addSubview:realTimeView];
        
        UILongPressGestureRecognizer *tap = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(realTap:)];
        [realTimeView addGestureRecognizer:tap];
    }
    
    //赋图层path属性
    if (lineLayer == nil) {
        lineLayer = [CAShapeLayer layer];
        lineLayer.fillColor = nil;
        lineLayer.frame = realTimeView.bounds;
        lineLayer.strokeColor = _lineColor.CGColor;
        lineLayer.lineCap = kCALineCapRound;
        lineLayer.contentsScale = [UIScreen mainScreen].scale;
        lineLayer.lineJoin = kCALineJoinRound;
        lineLayer.backgroundColor = nil;
        [realTimeView.layer addSublayer:lineLayer];
    }
    lineLayer.lineWidth = _lineWidth;
    lineLayer.path = nil;
    lineLayer.path = paths.CGPath;
    
    //封闭区间
    UIBezierPath *path1 = [UIBezierPath bezierPathWithCGPath:paths.CGPath];
    CGPoint lastPoint = paths.currentPoint;
    lastPoint.y = 0;
    [path1 addLineToPoint:lastPoint];
    CGPoint startPoint = [self startPoint];
    [path1 addLineToPoint:CGPointMake(startPoint.x, 0)];
    [path1 addLineToPoint:startPoint];
    
    if (shaperLayer == nil) {
        shaperLayer = [CAShapeLayer layer];
        shaperLayer.magnificationFilter = kCAFilterNearest;
    }
    //一定要是一条封闭的环
    shaperLayer.path = nil;
    shaperLayer.path = path1.CGPath;
    
    if (gradientLayer == nil) {
        gradientLayer = [CAGradientLayer layer];
        gradientLayer.frame = realTimeView.bounds;
        gradientLayer.type = kCAGradientLayerAxial;
        gradientLayer.contentsScale = [UIScreen mainScreen].scale;
        gradientLayer.startPoint = CGPointMake(0, 1);
        gradientLayer.endPoint = CGPointMake(0, 0);
        gradientLayer.locations = @[@0.25, @1];
        gradientLayer.colors = _gradientColor;
        /**
         CALayer有一个属性叫做mask可以解决这个问题。这个属性本身就是个CALayer类型，有和其他图层一样的绘制和布局属性。它类似于一个子图层，相对于父图层（即拥有该属性的图层）布局，但是它却不是一个普通的子图层。不同于那些绘制在父图层中的子图层，mask图层定义了父图层的部分可见区域。
         mask图层的Color属性是无关紧要的，真正重要的是图层的轮廓。mask属性就像是一个饼干切割机，mask图层实心的部分会被保留下来，其他的则会被抛弃。（如图4.12）
         如果mask图层比父图层要小，只有在mask图层里面的内容才是它关心的，除此以外的一切都会被隐藏起来。
         */
        //将渐变图层的mask设置为shaperLayer这样就只有那个切割过的渐变效果了
        [realTimeView.layer addSublayer:gradientLayer];
        if (midLayer) {
            [realTimeView.layer insertSublayer:midLayer above:gradientLayer];
        }
    }
    gradientLayer.mask = shaperLayer;
    
    [self setLabTextLayerText];
    if ([self.delegate respondsToSelector:@selector(gradientLayerViewDidDraw:)]) {
        [self.delegate gradientLayerViewDidDraw:self];
    }
}

- (void)addPoint:(NSNumber *)point isNew:(BOOL)newFlag{
    if (point) {
        NSDate *date1 = [NSDate date];
        CGAffineTransform transform = CGAffineTransformIdentity;
        BOOL requireCompareAll = NO;
        if (newFlag) {
            if (pointArray.count >= _maxCount) {
                double firstHeight = [pointArray[startIndexAtArray] doubleValue];
                requireCompareAll = (firstHeight >= (maxHeight - SHADOWNHEIGHT * (maxHeight - minHeight)));
            }
//            [pointArray addObject:point];
            startIndexAtArray++;
            transform = CGAffineTransformTranslate(transform, -everyXSpace, 0);
        }else{
//            [pointArray replaceObjectAtIndex:pointArray.count-1 withObject:point];
        }
#if 0
        //别蛋疼了,重新绘制还快些.
        if (requireCompareAll) {
            [self drawLine];
        }else{
            CGFloat firstSpace = maxHeight - minHeight;
            CGFloat lastPoint = point.doubleValue;
            //获取当前点位在之前坐标系中的位置
            CGFloat nowPathPoint = [self yHeight:lastPoint];
//            UIBezierPath *path1 = [self pathAddPath:path LastHeight:nowPathPoint];
            //先缩放比例,然后把最后一个点添加上
            UIBezierPath *path1 = [UIBezierPath bezierPathWithCGPath:path.CGPath];
            if (newFlag) {
                [path addLineToPoint:CGPointMake(path.currentPoint.x + everyXSpace, nowPathPoint)];
                [path applyTransform:transform];
            }
            maxArrayHeight = maxArrayHeight > lastPoint ? maxArrayHeight : lastPoint;
            minArrayHeight = lastPoint > minArrayHeight ? minArrayHeight : lastPoint;
            [self getLastMaxAndMinHeightByLastHeight:lastPoint];
            //缩放比例(物理缩放比例)
            CGFloat lastSpace = maxHeight - minHeight;
            CGFloat scale = firstSpace/lastSpace;
            transform = CGAffineTransformScale(transform, 1, scale);
            [path1 applyTransform:transform];
            //获取当前点位在现在坐标系中的位置
            CGFloat nowLastPoint = [self yHeight:lastPoint];
            //平移UIBezierPath的位置,是否需要缩放,需要缩放的
            CGFloat lastYTranslate = nowLastPoint - path1.currentPoint.y;
            transform = CGAffineTransformTranslate(transform, 0, lastYTranslate);
            [path1 applyTransform:transform];
            NSLog(@"path1 lastYHeight = %f, calculate = %f, scale = %f", path1.currentPoint.y, [self yHeight:[[pointArray lastObject] doubleValue]], scale);
            [self setCoreLayerPath:path1];
        }
#else
        [self drawLine];
#endif
        NSDate *date2 = [NSDate date];
        NSLog(@"新数据来时转换用了多久%lf", [date2 timeIntervalSinceDate:date1]);
    }
}

#pragma mark - 长按手势
- (void)realTap:(UILongPressGestureRecognizer *)ges {
    CGPoint point = [ges locationInView:ges.view];
    curPointValue = [NSValue valueWithCGPoint:point];
    [self createSubLayer];
    if (ges.state == UIGestureRecognizerStateBegan) {
        if (_layerType == LayerType_RealTime) {
            [realTimeView.layer addSublayer:rvLayer];
            [realTimeView.layer addSublayer:circleLayer];
            [realTimeView.layer addSublayer:showPriceLayer];
        }else{
            [kView.layer addSublayer:rvLayer];
            [kView.layer addSublayer:circleLayer];
            [kView.layer addSublayer:showPriceLayer];
        }
    } else if (ges.state == UIGestureRecognizerStateEnded) {
        [rvLayer removeFromSuperlayer];
        [showPriceLayer removeFromSuperlayer];
        [circleLayer removeFromSuperlayer];
        curPointValue = nil;
        return;
    }
    [self showInfoAtPoint:point];
}

- (void)showInfoAtPoint:(CGPoint)point {
    NSInteger index = (int)round(point.x / everyXSpace) - startIndex;
    if (point.x <= startIndex*everyXSpace) {
        index = 0;
    } else if (point.x >= (_maxCount - 1) * everyXSpace) {
        index = currentCount - 1;
    }
    [self showInfoByIndex:index];
}

static const CGFloat showSpace = 10;
//传递数组的位置索引
- (void)showInfoByIndex:(NSInteger)index {
    NSInteger start = startIndexAtArray + index;
    NSString *price = closeArray[start];
    NSString *date = [toDateFormatter stringFromDate:[dateFormatter dateFromString:[pointArray[start] lastObject]]];
    CGFloat y = [self yHeight:[price doubleValue]];
    CGFloat x = (startIndex + index) * everyXSpace;
    circleLayer.position = CGPointMake(x, y);
    
    CGRect frame = rvLayer.frame;
    frame.origin.x = x;
    rvLayer.frame = frame;
    
    showPriceLayer.string = [NSString stringWithFormat:@"%@\n%@", date, [price strNumberByScale:_scale]];
    CGRect frame1 = showPriceLayer.frame;
    if (CGRectGetWidth(showPriceLayer.frame) + showSpace > x) {
        frame1.origin.x = x + showSpace;
    }else{
        frame1.origin.x = x - showSpace - CGRectGetWidth(showPriceLayer.frame);
    }
    frame1.origin.y = y - CGRectGetHeight(showPriceLayer.frame) / 2.0;
    showPriceLayer.frame = frame1;
}

- (void)createSubLayer {
    if (rvLayer == nil) {
        rvLayer = [CAShapeLayer layer];
        rvLayer.frame = CGRectMake(0, _edgeInsets.top, _midLineWidth, CGRectGetHeight(innerRect));
        rvLayer.backgroundColor = [UIColor whiteColor].CGColor;
        [self addXuLineInLayer:rvLayer lineArray:nil vertiacal:YES];
    }
    
    if (circleLayer == nil) {
        circleLayer = [CAShapeLayer layer];
        circleLayer.frame = CGRectMake(0, 0, 4, 4);
        circleLayer.path = [UIBezierPath bezierPathWithRoundedRect:circleLayer.bounds cornerRadius:CGRectGetWidth(circleLayer.bounds)/2].CGPath;
        circleLayer.strokeColor = [UIColor whiteColor].CGColor;
        circleLayer.fillColor = [UIColor whiteColor].CGColor;
    }
    
    if (showPriceLayer == nil) {
        showPriceLayer = [CATextLayer layer];
        showPriceLayer.foregroundColor = [UIColor blackColor].CGColor;
        showPriceLayer.backgroundColor = [UIColor whiteColor].CGColor;
        showPriceLayer.contentsScale = [UIScreen mainScreen].scale;
        showPriceLayer.fontSize = _labFontSize;
        showPriceLayer.frame = CGRectMake(0, 0, 50, 30);
        showPriceLayer.alignmentMode = kCAAlignmentCenter;
        showPriceLayer.cornerRadius = 5.0f;
        showPriceLayer.masksToBounds = YES;
        showPriceLayer.shadowOffset = CGSizeMake(2, 2);
        showPriceLayer.shadowRadius = 5.0f;
        showPriceLayer.shadowColor = [UIColor yellowColor].CGColor;
    }
}

#pragma mark - 布局相关
//虚线条尺寸
static CGFloat number[] = {5, 5};
/**
 *  @author zmj, 16-02-28 10:02:31
 *
 *  更新边界相关的方法
 */
- (void)updateBorder {
    
    innerRect = CGRectMake(_edgeInsets.left, _edgeInsets.top, CGRectGetWidth(self.bounds) - _edgeInsets.left - _edgeInsets.right, CGRectGetHeight(self.bounds) - _edgeInsets.top - _edgeInsets.bottom);

    [self addBorderLayer];

    CGRect frame = innerRect;
    frame.origin.x = 0.f;
    frame.origin.y = CGRectGetMidY(innerRect) - _midLineWidth / 2;
    frame.size.height = _midLineWidth;
    
    if (midLayer == nil) {
        midLayer = [CAShapeLayer layer];
        midLayer.frame = frame;
        [self addXuLineInLayer:midLayer lineArray:nil vertiacal:NO];
    }
    
    if (_layerType == LayerType_RealTime) {
        [realTimeView.layer addSublayer:midLayer];
    }else{
        [kView.layer addSublayer:midLayer];
    }
    
    CGRect frame1 = innerRect;
    frame1.size.height = LABHEIGHT;
    frame1.origin.y = CGRectGetMidY(innerRect) - frame.size.height / 2;
    if (labInRight) {
        frame1.origin.x += (CGRectGetWidth(frame) + LABSPACETOEDGE);
        frame1.size.width = _edgeInsets.right - LABSPACETOEDGE;
    }else{
        frame1.origin.x = 0;
        frame1.size.width = _edgeInsets.left;
    }
    if (curTextLayer == nil) {
        curTextLayer = [CATextLayer layer];
        curTextLayer.frame = frame1;
        curTextLayer.cornerRadius = 3.0;
        curTextLayer.masksToBounds = YES;
        curTextLayer.shouldRasterize = YES;
        curTextLayer.rasterizationScale = [UIScreen mainScreen].scale;
        curTextLayer.alignmentMode = labInRight ? kCAAlignmentLeft : kCAAlignmentRight;
        curTextLayer.foregroundColor = [UIColor blackColor].CGColor;
        curTextLayer.contentsScale = [UIScreen mainScreen].scale;
        curTextLayer.fontSize = _labFontSize;
        curTextLayer.backgroundColor = [UIColor whiteColor].CGColor;
        [self.layer addSublayer:curTextLayer];
    }
    id number = [closeArray lastObject];
    NSString *str = [number isKindOfClass:[NSNumber class]] ? [number stringValue]: number;
    curTextLayer.string = [str strNumberByScale:_scale];
}

- (void)addBorderLayer {
    if (borderLayer == nil) {
        borderLayer = [CALayer layer];
        borderLayer.frame = innerRect;
        borderLayer.backgroundColor = nil;
        borderLayer.masksToBounds = YES;
        [self.layer addSublayer:borderLayer];
    }
    
    CGFloat yspace = CGRectGetHeight(innerRect) / (LABCOUNT - 1);
    //设置文本layer的位置
    [self setLabTextLayerYspace:yspace];
    
#pragma mark 绘制背景图片,异步绘制
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        UIGraphicsBeginImageContextWithOptions(innerRect.size, YES, [UIScreen mainScreen].scale);
        CGContextRef context = UIGraphicsGetCurrentContext();
        UIBezierPath *paths = [UIBezierPath bezierPathWithRect:borderLayer.bounds];
        [_borderBackgroundColor setFill];
        [paths fill];
        //水平
        UIBezierPath *path1 = [UIBezierPath bezierPath];
        for (NSInteger i = 0; i < LABCOUNT - 1; i++) {
            CGFloat y = (i + 1) * yspace;
            [path1 moveToPoint:CGPointMake(0, y)];
            [path1 addLineToPoint:CGPointMake(innerRect.size.width, y)];
        }
        if (_backgroundLineType == backLineType_Dash) {
            [path1 setLineDash:number count:2 phase:0];
        }
        path1.lineCapStyle = kCGLineCapRound;
        path1.lineWidth = _borderHorizonlLineWidth;
        [_borderHorizonlColor setStroke];
        [path1 stroke];
        //垂直
        UIBezierPath *path2 = [UIBezierPath bezierPath];
        CGFloat xspace = CGRectGetWidth(innerRect) / (VERTICALCOUNT - 1);
        for (NSInteger i = 0; i < VERTICALCOUNT - 2; i++) {
            CGFloat x = (i + 1) * xspace;
            [path2 moveToPoint:CGPointMake(x, 0)];
            [path2 addLineToPoint:CGPointMake(x, innerRect.size.height)];
        }
        if (_backgroundLineType == backLineType_Dash) {
            [path2 setLineDash:number count:2 phase:0];
        }
        path2.lineCapStyle = kCGLineCapRound;
        path2.lineWidth = _borderVerticalLineWidth;
        [_borderVerticalColor setStroke];
        [path2 stroke];
        CGContextAddPath(context, path2.CGPath);
        CGContextSetLineDash(context, 0, number, 2);
        CGContextAddPath(context, path1.CGPath);
        CGContextDrawPath(context, kCGPathFillStroke);
        CGContextStrokePath(context);
        UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        dispatch_async(dispatch_get_main_queue(), ^{
            borderLayer.contents = (__bridge id)image.CGImage;
        });
    });
}

- (void)addXuLineInLayer:(CAShapeLayer *)layer lineArray:(NSArray *)numbers vertiacal:(BOOL)flag {
    NSArray *arr = numbers;
    if (arr == nil) {
        arr = @[@5, @5];
    }
    UIBezierPath *path1 = [UIBezierPath bezierPath];
    [path1 moveToPoint:CGPointZero];
    if (flag) {
        [path1 addLineToPoint:CGPointMake(0, CGRectGetHeight(layer.bounds))];
    }else{
        [path1 addLineToPoint:CGPointMake(CGRectGetWidth(layer.frame), 0)];
    }
    layer.path = path1.CGPath;
    layer.lineWidth = _midLineWidth;
    layer.lineDashPattern = @[@5, @5];
    layer.backgroundColor = [UIColor clearColor].CGColor;
    layer.strokeColor = _midLineColor.CGColor;
}
//设置文本的位置
- (void)setLabTextLayerYspace:(CGFloat)space{
    if (labVTextArray == nil) {
        NSMutableArray *layArray = @[].mutableCopy;
        CGFloat everyHeight = (maxHeight - minHeight) / LABCOUNT;
        for (NSInteger i = 0; i < LABCOUNT - 2; i++) {
            CATextLayer *layer = [CATextLayer layer];
            layer.contentsScale = [UIScreen mainScreen].scale;
            layer.fontSize = _labFontSize;
            layer.foregroundColor = _labForegroundColor.CGColor;
            layer.backgroundColor = self.layer.backgroundColor;
            [self.layer addSublayer:layer];
            [layArray addObject:layer];
            layer.string = @(maxArrayHeight - i * everyHeight).stringValue;
            if (labInRight) {
                layer.alignmentMode = kCAAlignmentLeft;
            }else{
                layer.alignmentMode = kCAAlignmentRight;
            }
        }
        labVTextArray = [layArray copy];
    }
    __block CGRect frame;
    if (labInRight) {
        frame = CGRectMake(CGRectGetWidth(self.bounds) - _edgeInsets.right + LABSPACETOEDGE, 0, _edgeInsets.right - LABSPACETOEDGE, LABHEIGHT);
    }else{
        frame = CGRectMake(0, 0, _edgeInsets.left, LABHEIGHT);
    }
    [labVTextArray enumerateObjectsUsingBlock:^(CATextLayer * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        frame.origin.y = (idx + 1) * space + _edgeInsets.top - LABHEIGHT / 2.0;
        obj.frame = frame;
    }];
    
    //水平时间标度
    if (labHTextArray == nil) {
        CGFloat hSpace = CGRectGetWidth(innerRect) / (VERTICALCOUNT - 1);
        CGFloat width = hSpace - 20;
        CGFloat x = _edgeInsets.left + hSpace - width / 2.0;
        NSMutableArray *tmpArray = @[].mutableCopy;
        for (NSInteger i = 0; i < VERTICALCOUNT - 2; i++) {
            CATextLayer *layer = [CATextLayer layer];
            layer.contentsScale = [UIScreen mainScreen].scale;
            layer.fontSize = _labFontSize;
            layer.foregroundColor = _labForegroundColor.CGColor;
            layer.backgroundColor = self.layer.backgroundColor;
            [self.layer addSublayer:layer];
            [tmpArray addObject:layer];
            layer.string = @"09:30";
            layer.alignmentMode = kCAAlignmentCenter;
            layer.frame = CGRectMake(x, CGRectGetMaxY(innerRect), width, _edgeInsets.bottom);
            x += hSpace;
        }
        labHTextArray = [tmpArray copy];
    }
}

- (void)setLabTextLayerText {
    //设置垂直高度和水平时间
    CGFloat everyHeight = (maxHeight - minHeight) / (LABCOUNT - 1);
    [labVTextArray enumerateObjectsUsingBlock:^(CATextLayer * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        obj.string = [[NSString stringWithFormat:@"%lf", maxArrayHeight - idx * everyHeight] strNumberByScale:_scale];
    }];
    id number = [closeArray lastObject];
    NSString *str = [number isKindOfClass:[NSNumber class]] ? [number stringValue]: number;
    curTextLayer.string = [str strNumberByScale:_scale];
    
    //设置水平时间
    NSUInteger vspace = _maxCount / (VERTICALCOUNT - 1);
    NSInteger index = startIndexAtArray + labHTextArray.count * vspace -1;
    if (index >= pointArray.count) {
        index = index - startIndex;
    }
    NSArray *showDataLastTimeArray = pointArray[index];
    NSDate *lastDate = [dateFormatter dateFromString:[showDataLastTimeArray lastObject]];
    [labHTextArray enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(CATextLayer * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSInteger space = (idx + 1 - labHTextArray.count) * vspace * 60;
        NSDate *date1 = [NSDate dateWithTimeInterval:space sinceDate:lastDate];
        obj.string = [toDateFormatter stringFromDate:date1];
    }];
    
    //垂直textLayer的frame
    CGRect frame = midLayer.frame;
    frame.origin.y = [self yHeight:[str doubleValue]];
    
    CGRect frame1 = [realTimeView convertRect:frame toView:self];
    CGRect originFrame = curTextLayer.frame;
    originFrame.origin.y = frame1.origin.y - LABHEIGHT / 2.0;
    [UIView animateWithDuration:0.1 animations:^{
        curTextLayer.frame = originFrame;
        midLayer.frame = frame;
    }];
    
    //设置十字光标信息
    if (curPointValue) {
        [self showInfoAtPoint:[curPointValue CGPointValue]];
    }
}

#pragma mark - 绘背景黑色图
- (UIImage *)drawBackgroundWithRect:(CGRect)rect cornerRadius:(CGFloat)radius fillColor:(UIColor *)color {
    UIGraphicsBeginImageContextWithOptions(rect.size, NO, [UIScreen mainScreen].scale);
    UIBezierPath *paths = [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:radius];
    [color setFill];
    [paths fill];
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}

@end
